/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.edu.unal.bioingenium.kbmed.data.loader;

import co.edu.unal.bioingenium.kbmed.data.PhysicalDocument;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;

/**
 *
 * @author Alejandro Riveros Cruz
 */
public class PDFLoader implements DocumentLoader {

    private final String type = "PDF";
    /**
     * 
     */
    public PDFLoader() {
    }

    /**
     * 
     * @param path
     * @return
     */
    @Override
    public PhysicalDocument parseDocument(String corpusPath, String fileName) {
        File file = new File(corpusPath +  fileName);
        if (!file.isFile()) {
            Logger.getLogger(TXTLoader.class.getName()).log(Level.WARNING, "The file {0}don''t exist.", corpusPath +  fileName);
            return null;
        }
        PDFParser parser;
        String parsedText = null;
        PDFTextStripper pdfStripper = null;
        PDDocument pdDocument = null;
        COSDocument cosDocumentc = null;
        PhysicalDocument document = null;
        try {
            parser = new PDFParser(new FileInputStream(file));
        } catch (IOException ioe) {
            Logger.getLogger(PDFLoader.class.getName()).log(Level.SEVERE, "Unable to open PDF parser", ioe);
            return null;
        }
        try {
            parser.parse();
            cosDocumentc = parser.getDocument();
            pdfStripper = new PDFTextStripper();
            pdDocument = new PDDocument(cosDocumentc);
            parsedText = pdfStripper.getText(pdDocument);
            document = new PhysicalDocument(fileName);
            document.setType(type);
            document.setSize(file.length());
            document.setLastModified(new Date(file.lastModified()));
            document.setContent(parsedText);
        } catch (IOException ioe) {
            Logger.getLogger(PDFLoader.class.getName()).log(Level.SEVERE, "Error while parsing PDF file" + corpusPath + File.pathSeparator + fileName, ioe);
        } finally {
            try {
                if (cosDocumentc != null) {
                    cosDocumentc.close();
                }
                if (pdDocument != null) {
                    pdDocument.close();
                }
            } catch (IOException ioe) {
                Logger.getLogger(PDFLoader.class.getName()).log(Level.SEVERE, "Error finalizing PDF parser", ioe);
            }
        }
        return document;
    }
}
